﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace TerrariViewer
{
    public partial class TerrariViewer : Form
    {
        #region Variables
        const int DPI_X_OFFSET = 80;
        const int DPI_Y_OFFSET = 24;

        private const string versionNumber = "5.2";
        private float dpiX;

        private Player APlayer;
        private string[] fileArray;
        private int equipmentClicked = -1;
        private int buffClicked = -1;
        private int invClicked = 0;
        private int bankClicked = 0;

        private string maxHealth = "400";
        private string maxMana = "260";

        private string[] equipment = new string[11];
        private Buff[] buffs = new Buff[10];
        private Item[] inv = new Item[48];
        private Item[] ammo = new Item[4];
        private Item[] bank = new Item[40];

        private Color tempColor = new Color();
        private Item tempItem = new Item();
        private Buff tempBuff = new Buff();
        private Random random = new Random();
        private UpdateChecker updateCheck = new UpdateChecker();

        private List<PictureBox> colorBoxes;
        private List<PictureBox> equipmentBoxes;
        private List<PictureBox> buffBoxes;
        private List<Label> buffLabels;
        private List<Label> bTimeLabels;
        private List<Label> invBoxes;
        private List<Label> bankBoxes;

        Bitmap hair;
        Bitmap head;
        Bitmap skin;
        Bitmap eyes;
        Bitmap shirt;
        Bitmap undershirt;
        Bitmap pants;
        Bitmap shoes;

        Control ctrl;
        Type type;
        PictureBox selectedBox;
        Label selectedLbl;
        #endregion

        #region Item Lists
        private List<string> items = new List<string> { };
        
        private List<string> armors = new List<string> { 
                                    
                                    "Copper Helmet",                                    
                                    "Diving Helmet", 
                                    "Goggles",                                    
                                    "Gold Helmet",                                    
                                    "Iron Helmet",
                                    "Jungle Hat",                                    
                                    "Meteor Helmet",                                    
                                    "Mining Helmet",
                                    "Molten Helmet",
                                    "Necro Helmet",                                    
                                    "Shadow Helmet",
                                    "Silver Helmet",                                    
                                    "Wizard Hat", 
                                    
                                    "Empty Bucket",
                                    "Archaeologist's Hat",
                                    "Bunny Hood",
                                    "Familiar Wig",
                                    "Fish Bowl",
                                    "Gold Crown",
                                    "Hero's Hat",
                                    "Jungle Rose",
                                    "Mime Mask",
                                    "Ninja Hood",
                                    "Plumber's Hat",
                                    "Red Hat",
                                    "Robot Hat",
                                    "Summer Hat",
                                    "Sunglasses",
                                    "Top Hat",                                   

                                    "Copper Chainmail",  
                                    "Gold Chainmail",
                                    "Jungle Shirt",
                                    "Iron Chainmail",
                                    "Meteor Suit",
                                    "Molten Breastplate",
                                    "Necro Breastplate",
                                    "Shadow Scalemail",
                                    "Silver Chainmail",

                                    "Archaeologist's Jacket",
                                    "The Doctor's Shirt",
                                    "Familiar Shirt",
                                    "Hero's Shirt",
                                    "Ninja Shirt",
                                    "Plumber's Shirt",
                                    "Robe",    
                                    "Tuxedo Shirt",

                                    "Copper Greaves",                                    
                                    "Gold Greaves", 
                                    "Iron Greaves",                                    
                                    "Jungle Pants", 
                                    "Meteor Leggings",                                    
                                    "Molten Greaves", 
                                    "Necro Greaves",
                                    "Shadow Greaves",
                                    "Silver Greaves",                                    

                                    "Archaeologist's Pants",
                                    "The Doctor's Pants",
                                    "Familiar Pants",
                                    "Hero's Pants",
                                    "Ninja Pants",                                    
                                    "Plumber's Pants",
                                    "Tuxedo Pants",  
        };

        private List<string> accs = new List<string> { 
                                    
                                    "Aglet",
                                    "Anklet of the Wind",
                                    "Band of Regeneration",
                                    "Band of Starpower",
                                    "Cloud in a Bottle",
                                    "Cobalt Shield",
                                    "Copper Watch",
                                    "Depth Meter",
                                    "Feral Claws",
                                    "Flipper",
                                    "Gold Watch",
                                    "Guide Voodoo Doll",
                                    "Hermes Boots",
                                    "Lucky Horseshoe",
                                    "Nature's Gift",
                                    "Obsidian Skull",
                                    "Rocket Boots",
                                    "Shackle",
                                    "Shiny Red Balloon",
                                    "Silver Watch",
        };

        private List<string> weapons = new List<string> { 
                                    
                                    "Aqua Scepter",
                                    "Ball 'O Hurt",
                                    "Blade of Grass",
                                    "Blowpipe",
                                    "Blue Moon",
                                    "Blue Phaseblade",
                                    "Copper Bow",
                                    "Copper Broadsword",
                                    "Copper Shortsword",
                                    "Dark Lance",
                                    "Demon Scythe",
                                    "Demon Bow",
                                    "Enchanted Boomerang",
                                    "Fiery Greatsword",
                                    "Flamarang",
                                    "Flamelash",
                                    "Flintlock Pistol",
                                    "Flower of Fire",
                                    "Gold Bow",
                                    "Gold Broadsword",
                                    "Gold Shortsword",
                                    "Green Phaseblade",
                                    "Handgun",
                                    "Harpoon",
                                    "Iron Bow",
                                    "Iron Broadsword",
                                    "Iron Shortsword",
                                    "Light's Bane",
                                    "Magic Missile",
                                    "Minishark",
                                    "Molten Fury",
                                    "Muramasa",
                                    "Musket",
                                    "Night's Edge",
                                    "Phoenix Blaster",
                                    "Purple Phaseblade",
                                    "Red Phaseblade",
                                    "Sandgun",
                                    "Silver Bow",
                                    "Silver Broadsword",
                                    "Silver Shortsword",
                                    "Space Gun",
                                    "Spear",
                                    "Staff of Regrowth",
                                    "Starfury",
                                    "Star Cannon",
                                    "Sunfury",
                                    "Thorn Chakrum",
                                    "Trident",
                                    "Vilethorn",
                                    "Water Bolt",
                                    "White Phaseblade",
                                    "Wooden Boomerang",
                                    "Wooden Bow",
                                    "Wooden Sword",
                                    "Yellow Phaseblade",
        };

        private List<string> tools = new List<string> {
                                    
                                    "Copper Axe",
                                    "Copper Hammer",
                                    "Copper Pickaxe",
                                    "Gold Axe",
                                    "Gold Hammer",
                                    "Gold Pickaxe",
                                    "Grappling Hook",
                                    "Iron Axe",
                                    "Iron Hammer",
                                    "Iron Pickaxe",
                                    "Ivy Whip",
                                    "Meteor Hamaxe",
                                    "Molten Hamaxe",
                                    "Molten Pickaxe",
                                    "Nightmare Pickaxe",
                                    "Silver Axe",
                                    "Silver Hammer",
                                    "Silver Pickaxe",
                                    "The Breaker",
                                    "War Axe of the Night",
                                    "Wooden Hammer",
        };

        private List<string> blocks = new List<string> { 
        
                                    "Ash Block",
                                    "Blue Brick",
                                    "Blue Brick Wall",
                                    "Clay Block",
                                    "Copper Bar",
                                    "Copper Brick",
                                    "Copper Brick Wall",
                                    "Copper Ore",
                                    "Demonite Bar",
                                    "Demonite Ore",
                                    "Dirt Block",
                                    "Dirt Wall",
                                    "Ebonstone Block",
                                    "Glass",
                                    "Gold Bar",
                                    "Gold Brick",
                                    "Gold Brick Wall",
                                    "Gold Ore",
                                    "Gray Brick",
                                    "Gray Brick Wall",
                                    "Green Brick",
                                    "Green Brick Wall",
                                    "Hellstone",
                                    "Hellstone Bar",
                                    "Hellstone Brick",
                                    "Iron Bar",
                                    "Iron Ore",
                                    "Meteorite Bar",
                                    "Meteorite",
                                    "Mud Block",
                                    "Obsidian",
                                    "Obsidian Brick",
                                    "Obsidian Brick Wall",
                                    "Pink Brick",
                                    "Pink Brick Wall",
                                    "Red Brick",
                                    "Red Brick Wall",
                                    "Sand Block",
                                    "Silver Bar",
                                    "Silver Brick",
                                    "Silver Brick Wall",
                                    "Silver Ore",
                                    "Spike",
                                    "Stone Block",
                                    "Stone Wall",
                                    "Wood",
                                    "Wood Wall",
        };

        private List<string> consumables = new List<string> { 

                                    "Acorn",
                                    "Bomb",
                                    "Bone",
                                    "Corrupt Seeds",
                                    "Dynamite",
                                    "Glowing Mushroom",
                                    "Goldfish",
                                    "Grass Seeds",
                                    "Grenade",
                                    "Healing Potion",
                                    "Jungle Grass Seeds",
                                    "Lesser Healing Potion",
                                    "Lesser Mana Potion",
                                    "Lesser Restoration Potion",
                                    "Life Crystal",
                                    "Mana Crystal",
                                    "Mana Potion",
                                    "Mushroom",
                                    "Mushroom Grass Seeds",
                                    "Purification Powder",
                                    "Restoration Potion",
                                    "Shuriken",
                                    "Spiky Ball",
                                    "Sticky Bomb",
                                    "Sunflower",
                                    "Suspicious Looking Eye",
                                    "Vile Powder",
                                    "Wood Platform",
                                    "Worm Food",
                                    "Throwing Knife",
                                    "Poisoned Knife",
                                    "Obsidian Skin Potion",
                                    "Regeneration Potion",
                                    "Swiftness Potion",
                                    "Gills potion",
                                    "Ironskin Potion",
                                    "Mana Regeneration Potion",
                                    "Magic Power Potion",
                                    "Featherfall Potion",
                                    "Spelunker Potion",
                                    "Invisibility Potion",
                                    "Shine Potion",
                                    "Night Owl Potion",
                                    "Battle Potion",
                                    "Thorns Potion",
                                    "Archery Potion",
                                    "Water Walking Potion",
                                    "Hunter Potion",
                                    "Gravitation Potion",
                                    "Moonglow Seeds",
                                    "Daybloom Seeds",
                                    "Blinkroot Seeds",
                                    "Deathweed Seeds",
                                    "Waterleaf Seeds",
                                    "Fireblossom Seeds",
                                    "Bottled Water", 
                                    // New with 1.0.6
                                    "Golden Key",
                                    "Shadow Key",
        };

        private List<string> furnitures = new List<string> {
            
                                    "Ale",
                                    "Bed",
                                    "Book",
                                    "Bottle",
                                    "Candle",
                                    "Chain Lantern",
                                    "Chest",
                                    "Clay Pot",
                                    "Copper Chandelier",
                                    "Coral",
                                    "Furnace",
                                    "Gold Chandelier",
                                    "Gold Chest",
                                    "Hellforge",
                                    "Iron Anvil",
                                    "Piggy Bank",
                                    "Sign",
                                    "Silver Chandelier",
                                    "Tombstone",
                                    "Torch",
                                    "Water Candle",                                    
                                    "Wooden Chair",
                                    "Wooden Door",
                                    "Wooden Table",
                                    "Work Bench",
                                    "Glowstick",
                                    "Sticky Glowstick",
                                    // New with 1.0.6
                                    "Piano",
                                    "Red Banner",
                                    "Green Banner",
                                    "Blue Banner",
                                    "Yellow Banner",
                                    "Chinese Lantern",
                                    "Barrel",
                                    "Cooking Pot",
                                    "Bookcase",
                                    "Candelabra",
                                    "Trash Can",
                                    "Throne",
                                    "Bowl",
                                    "Toilet",
                                    "Grandfather Clock",
                                    "Statue",
                                    "Bathtub",
                                    "Skull Lantern",
                                    "Tiki Torch",
                                    "Lamp Post",
                                    "Dresser",
                                    "Bench",
                                    "Loom",
                                    "Shadow Chest",
                                    "Goblin Battle Standard",
                                    "Safe",
                                    "Pink Vase",
                                    "Keg",                                    
                                    "Bowl of Soup",
                                    "Sawmill",
        };

        private List<string> misc = new List<string> { 
        
                                    "Amethyst",
                                    "Angel Statue",
                                    "Black Dye",
                                    "Black Lens",
                                    "Breathing Reed",
                                    "Cobweb",
                                    "Copper Coin",
                                    "Diamond",
                                    "Dirt Rod",
                                    "Emerald",
                                    "Empty Bucket",
                                    "Gel",
                                    "Gold Coin",
                                    "Green Dye",
                                    "Hook",
                                    "Iron Chain",
                                    "Jungle Spores",
                                    "Lava Bucket",
                                    "Leather",
                                    "Lens",
                                    "Magic Mirror", 
                                    "Mug",
                                    "Orb of Light",
                                    "Platinum Coin",
                                    "Rotten Chunk",
                                    "Ruby",
                                    "Sapphire",
                                    "Shadow Scale",
                                    "Silk",
                                    "Silver Coin",
                                    "Stinger",
                                    "Tattered Cloth",
                                    "Topaz",
                                    "Vile Mushroom",
                                    "Vine",
                                    "Water Bucket",
                                    "Whoopie Cushion",
                                    "Worm Tooth",
                                    "Cactus",
                                    "Daybloom",                                    
                                    "Moonglow",
                                    "Blinkroot",
                                    "Deathweed",
                                    "Waterleaf",
                                    "Fireblossom",
                                    "Shark Fin",
                                    "Feather",
                                    "Illegal Gun Parts",
                                    "Antlion Mandible",
        };

        private List<string> ammunition = new List<string> {   
 
                                    "Fallen Star",
                                    "Flaming Arrow",
                                    "Hellfire Arrow",
                                    "Jester's Arrow",
                                    "Meteor Shot",
                                    "Musket Ball",
                                    "Unholy Arrow",
                                    "Wooden Arrow",
                                    "Silver Bullet",
                                    "Seed",
        };
        #endregion

        public TerrariViewer()
        {
            InitializeComponent();
            this.Text = "TerrariViewer v" + versionNumber;

            imageList.Images.Add(Properties.Resources.Item_29);
            imageList.Images.Add(Properties.Resources.Item_251);
            imageList.Images.Add(Properties.Resources.Buff_1);
            imageList.Images.Add(Properties.Resources.Item_48);
            imageList.Images.Add(Properties.Resources.Item_346);
            imageList.ImageSize = new Size(16, 16);
            tabControl.ImageList = imageList;

            int index = 0;
            foreach (TabPage tab in tabControl.TabPages)
            {
                tab.ImageIndex = index;
                index++;
            }

            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\My Games\Terraria\Players";
            
            #region Form Lists
            items.AddRange(weapons.Union(tools).Union(armors).Union(accs).Union(blocks).Union(consumables).Union(furnitures).Union(misc).Union(ammunition));
            items.Sort();

            colorBoxes = new List<PictureBox> {
                hairClrBox, skinClrBox, eyeClrBox, shirtClrBox, ushirtClrBox, pantsClrBox, shoeClrBox };

            equipmentBoxes = new List<PictureBox> {
                armorBox1, armorBox2, armorBox3, accBox1, accBox2, accBox3, accBox4, accBox5, vanityBox1, vanityBox2, vanityBox3 };

            buffBoxes = new List<PictureBox> {
                buffBox1, buffBox2, buffBox3, buffBox4, buffBox5, buffBox6, buffBox7, buffBox8, buffBox9, buffBox10 };

            buffLabels = new List<Label> {
                buffLbl1, buffLbl2, buffLbl3, buffLbl4, buffLbl5, buffLbl6, buffLbl7, buffLbl8, buffLbl9, buffLbl10 };

            bTimeLabels = new List<Label> {
                bTimeLbl1, bTimeLbl2, bTimeLbl3, bTimeLbl4, bTimeLbl5, bTimeLbl6, bTimeLbl7, bTimeLbl8, bTimeLbl9, bTimeLbl10 };

            invBoxes = new List<Label> {
                inv1, inv2, inv3, inv4, inv5, inv6, inv7, inv8, inv9, inv10,
                inv11, inv12, inv13, inv14, inv15, inv16, inv17, inv18, inv19, inv20,
                inv21, inv22, inv23, inv24, inv25, inv26, inv27, inv28, inv29, inv30,
                inv31, inv32, inv33, inv34, inv35, inv36, inv37, inv38, inv39, inv40,
                inv41, inv42, inv43, inv44, inv45, inv46, inv47, inv48 };

            bankBoxes = new List<Label> {
                bank1, bank2, bank3, bank4, bank5, bank6, bank7, bank8, bank9, bank10, 
                bank11, bank12, bank13, bank14, bank15, bank16, bank17, bank18, bank19, bank20,
                bank21, bank22, bank23, bank24, bank25, bank26, bank27, bank28, bank29, bank30,
                bank31, bank32, bank33, bank34, bank35, bank36, bank37, bank38, bank39, bank40 };
            #endregion 

            using (Graphics g = CreateGraphics())
            {
                dpiX = g.DpiX;
            }

            if (dpiX == 120.0)
            {
                this.Size = new Size(691, 532);
                tabControl.Size = new Size(689, 462);
            }
            else
            {
                this.Size = new Size(521, 440);
                tabControl.Size = new Size(518, 387);
            }

            LoadForm();
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dpiX == 120.0)
            {
                switch (tabControl.SelectedIndex)
                {
                    case 0:
                        this.Size = new Size(691, 532);
                        tabControl.Size = new Size(689, 462);
                        break;

                    case 1:
                        this.Size = new Size(703, 467);
                        tabControl.Size = new Size(701, 402);
                        break;

                    case 2:
                        this.Size = new Size(914, 542);
                        tabControl.Size = new Size(912, 478);
                        break;

                    case 3:
                        invCategories.SelectedIndex = 0;
                        this.Size = new Size(1186, 540);
                        tabControl.Size = new Size(1184, 475);
                        break;

                    case 4:
                        bankCategories.SelectedIndex = 0;
                        this.Size = new Size(1046, 540);
                        tabControl.Size = new Size(1044, 475);
                        break;
                }
            }
            else
            {
                switch (tabControl.SelectedIndex)
                {
                    case 0:
                        this.Size = new Size(521, 440);
                        tabControl.Size = new Size(518, 387);
                        break;

                    case 1:
                        this.Size = new Size(530, 377);
                        tabControl.Size = new Size(527, 325);
                        break;

                    case 2:
                        this.Size = new Size(689, 441);
                        tabControl.Size = new Size(686, 388);
                        break;

                    case 3:
                        invCategories.SelectedIndex = 0;
                        this.Size = new Size(891, 440);
                        tabControl.Size = new Size(889, 386);
                        break;

                    case 4:
                        bankCategories.SelectedIndex = 0;
                        this.Size = new Size(789, 440);
                        tabControl.Size = new Size(786, 386);
                        break;
                }
            }
        }

        private void LoadForm()
        {
            APlayer = null;
            saveToolStripMenuItem.Enabled = false;

            //
            // Character Tab
            //
            nameTxtBox.Text = "Player Name";
            versionLbl.Text = "v 1.0.5";
            difficultyNum.Value = 0;
            cheatCheck.Checked = false;

            maxHealthTxtBox.Text = "200";
            healthTxtBox.Text = "100";
            maxManaTxtBox.Text = "0";
            manaTxtBox.Text = "0";

            hairClrBox.BackColor = tempColor.GetColor(215, 90, 55);
            skinClrBox.BackColor = tempColor.GetColor(255, 125, 75);
            eyeClrBox.BackColor = tempColor.GetColor(105, 90, 75);
            shirtClrBox.BackColor = tempColor.GetColor(175, 165, 140);
            ushirtClrBox.BackColor = tempColor.GetColor(160, 180, 215);
            pantsClrBox.BackColor = tempColor.GetColor(255, 230, 175);
            shoeClrBox.BackColor = tempColor.GetColor(160, 106, 60);
            hairNum.Value = 1;           

            this.Refresh();

            //
            // Equipment Tab
            //
            equipmentLV.Clear();
            foreach (PictureBox box in equipmentBoxes)
                box.Image = tempItem.ItemImage();

            for (int i = 0; i < equipment.Length; i++)
            {
                equipment[i] = "";
                equipmentBoxes[i].BorderStyle = BorderStyle.FixedSingle;
            }

            //
            // Buff Tab
            //
            for (int i = 0; i < tempBuff.buffName.Count; i++)
                buffLV.Items.Add(tempBuff.buffName[i]);

            foreach (PictureBox box in buffBoxes)
                box.Image = tempBuff.BuffImages();

            for (int i = 0; i < buffBoxes.Count; i++)
            {
                this.buffs[i] = new Buff();
                buffBoxes[i].Image = tempBuff.BuffImages();
                buffLabels[i].Text = "";
                bTimeLabels[i].Text = "";
                buffBoxes[i].BorderStyle = BorderStyle.FixedSingle;
            }

            //
            // Inventory Tab
            //
            invSearchTxtBox.Text = "";
            invCategories.SelectedIndex = 0;
            for (int i = 0; i < invBoxes.Count; i++)
            {
                this.inv[i] = new Item();
                invBoxes[i].Image = tempItem.ItemImage();
                invBoxes[i].Text = "0";
                invBoxes[i].BorderStyle = BorderStyle.FixedSingle;
            }

            currInvBox.Image = tempItem.ItemImage();
            currInvLbl.Text = "";
            invStackTxtBox.Enabled = false;
            invStackTxtBox.Text = "0";
            invBoxes[0].BorderStyle = BorderStyle.Fixed3D;
            invBoxes[0].BackColor = System.Drawing.Color.FromArgb(222, 222, 222);

            //
            // Bank Tab
            //
            bankSearchTxtBox.Text = "";
            bankCategories.SelectedIndex = 0;
            for (int i = 0; i < bankBoxes.Count; i++)
            {
                this.bank[i] = new Item();
                bankBoxes[i].Image = tempItem.ItemImage();
                bankBoxes[i].Text = "0";
                bankBoxes[i].BorderStyle = BorderStyle.FixedSingle;
            }

            currBankBox.Image = tempItem.ItemImage();
            currBankLbl.Text = "";
            bankStackTxtBox.Enabled = false;
            bankStackTxtBox.Text = "0";
            bankBoxes[0].BorderStyle = BorderStyle.Fixed3D;
            bankBoxes[0].BackColor = System.Drawing.Color.FromArgb(222, 222, 222);
        }


        #region File Controls
        private void LoadFile(string path)
        {
            APlayer = new Player(path);
            saveFileDialog.InitialDirectory = Path.GetDirectoryName(path);
            APlayer.LoadPlayer("");
            cheatCheck.Checked = CheatChecker();

            //
            // Initializes values for the Character Tab
            //
            if (APlayer.GameVersion >= 15)
                versionLbl.Text = "v 1.0.6";
            else if (APlayer.GameVersion >= 11 && APlayer.GameVersion < 15)
                versionLbl.Text = "v 1.0.5";
            else if (APlayer.GameVersion >= 6 && APlayer.GameVersion < 11)
                versionLbl.Text = "v 1.0.4";
            else
                versionLbl.Text = "v 1.0.3";

            nameTxtBox.Text = APlayer.CharName;
            difficultyNum.Value = (decimal)APlayer.Difficulty;
            genderCheck.Checked = APlayer.Gender;
            maxHealthTxtBox.Text = APlayer.MaxLife.ToString();
            healthTxtBox.Text = APlayer.CurrentLife.ToString();
            maxManaTxtBox.Text = APlayer.MaxMana.ToString(); ;
            manaTxtBox.Text = APlayer.CurrentMana.ToString();

            for (int i = 0; i < colorBoxes.Count; i++)
            {
                colorBoxes[i].BackColor = APlayer.Colors[i].GetColor();
            }

            hairNum.Value = (decimal)APlayer.CharHairType + 1;

            this.Refresh();

            //
            // Equipment Tab
            //
            for (int i = 0; i < equipmentBoxes.Count; i++)
            {
                equipmentBoxes[i].BorderStyle = BorderStyle.FixedSingle;
                equipment[i] = APlayer.armor[i].Name;
                equipmentBoxes[i].Image = APlayer.armor[i].ItemImage();
                toolTip.SetToolTip(equipmentBoxes[i], equipment[i]);
            }

            //
            // Buff Tab
            //
            for (int i = 0; i < buffBoxes.Count; i++)
            {
                this.buffs[i] = APlayer.buffs[i];
                buffBoxes[i].BorderStyle = BorderStyle.FixedSingle;
                buffBoxes[i].Image = this.buffs[i].BuffImages();
                if (buffs[i].BuffType > 0)
                {
                    buffLabels[i].Text = this.buffs[i].buffName[this.buffs[i].BuffType];
                    bTimeLabels[i].Text = (this.buffs[i].BuffTime / 60).ToString() + " Seconds";
                    toolTip.SetToolTip(buffBoxes[i], buffs[i].ToString());
                }
                else
                {
                    buffLabels[i].Text = "";
                    bTimeLabels[i].Text = "";
                }
            }

            //
            // Inventory Tab
            //
            invSearchTxtBox.Text = "";
            for (int i = 0; i < invBoxes.Count; i++)
            {
                this.inv[i] = APlayer.inv[i];
                invBoxes[i].BorderStyle = BorderStyle.FixedSingle;
                invBoxes[i].Image = this.inv[i].ItemImage();
                invBoxes[i].Text = this.inv[i].StackSize.ToString();
                toolTip.SetToolTip(invBoxes[i], inv[i].ToString());
            }

            currInvBox.Image = this.inv[0].ItemImage();
            currInvLbl.Text = this.inv[0].Name;
            invStackTxtBox.Enabled = true;
            invStackTxtBox.Text = this.inv[0].StackSize.ToString();
            invBoxes[0].BorderStyle = BorderStyle.Fixed3D;
            invBoxes[0].BackColor = System.Drawing.Color.FromArgb(208, 208, 208);
            toolTip.SetToolTip(currInvBox, inv[0].ToString());

            if (invStackTxtBox.Text == "0")
                invStackTxtBox.Enabled = false;

            //
            // Bank Tab
            //
            bankSearchTxtBox.Text = "";
            for (int i = 0; i < bankBoxes.Count; i++)
            {
                this.bank[i] = APlayer.bank[i];
                bankBoxes[i].BorderStyle = BorderStyle.FixedSingle;
                bankBoxes[i].Image = this.bank[i].ItemImage();
                bankBoxes[i].Text = this.bank[i].StackSize.ToString();
                toolTip.SetToolTip(bankBoxes[i], bank[i].ToString());
            }

            currBankBox.Image = this.bank[0].ItemImage();
            currBankLbl.Text = this.bank[0].Name;
            bankStackTxtBox.Enabled = true;
            bankStackTxtBox.Text = this.bank[0].StackSize.ToString();
            bankBoxes[0].BorderStyle = BorderStyle.Fixed3D;
            bankBoxes[0].BackColor = System.Drawing.Color.FromArgb(208, 208, 208);
            toolTip.SetToolTip(currBankBox, bank[0].ToString());

            if (bankStackTxtBox.Text == "0")
                bankStackTxtBox.Enabled = false;

            saveToolStripMenuItem.Enabled = true;
        }

        private void SaveFile()
        {
            APlayer.GameVersion = 20;
            APlayer.CharName = nameTxtBox.Text;
            APlayer.Difficulty = (byte)difficultyNum.Value;
            APlayer.CharHairType = (int)(hairNum.Value - 1);
            APlayer.CurrentLife = int.Parse(healthTxtBox.Text);
            APlayer.MaxLife = int.Parse(maxHealthTxtBox.Text);
            APlayer.CurrentMana = int.Parse(manaTxtBox.Text);
            APlayer.MaxMana = int.Parse(maxManaTxtBox.Text);

            for (int i = 0; i < APlayer.Colors.Length; i++)
            {
                APlayer.Colors[i].R = colorBoxes[i].BackColor.R;
                APlayer.Colors[i].G = colorBoxes[i].BackColor.G;
                APlayer.Colors[i].B = colorBoxes[i].BackColor.B;
            }

            for (int i = 0; i < 44; i++)
            {
                if (i < 11)
                    APlayer.armor[i].Name = equipment[i];

                APlayer.inv[i] = this.inv[i];

                if (i < 40)
                {
                    APlayer.bank[i] = this.bank[i];
                }

                if (i < 10)
                {
                    APlayer.buffs[i] = this.buffs[i];
                }
            }
        }

        private bool CheatChecker()
        {
            if (APlayer.MaxLife > 400 || APlayer.MaxMana > 260)
            {
                return true;
            }

            for (int i = 0; i < APlayer.buffs.Length; i++)
            {
                if (APlayer.buffs[i].BuffTime > (APlayer.buffs[i].MaxBuff() * 60))
                    return true;                
            }

            for (int i = 0; i < APlayer.inv.Length; i++)
            {
                if (!String.IsNullOrEmpty(APlayer.inv[i].Name))
                {
                    if (APlayer.inv[i].StackSize > APlayer.inv[i].ItemMaxStack())
                        return true;
                }
            }

            for (int i = 0; i < APlayer.bank.Length; i++)
            {
                if (!String.IsNullOrEmpty(APlayer.bank[i].Name))
                {
                    if (APlayer.bank[i].StackSize > APlayer.bank[i].ItemMaxStack())
                        return true;
                }
            }

            return false;
        }

        #endregion

        #region ToolStrip
        private void FileArray()
        {
            try
            {
                fileArray = Directory.GetFileSystemEntries(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\My Games\Terraria\Players", "*.plr", SearchOption.TopDirectoryOnly);
            }
            catch(Exception exception)
            {
                Console.WriteLine(exception);
            }

            fileComboBox.MaxDropDownItems = fileArray.Length;
            fileComboBox.Items.Clear();
            for (int i = 0; i < fileArray.Length; i++)
            {
                fileComboBox.Items.Add(Path.GetFileNameWithoutExtension(fileArray[i]));
            }
        }

        private void fileComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadFile(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\My Games\Terraria\Players\" + fileComboBox.SelectedItem.ToString() + ".plr");
        }

        private void fileComboBox_Click(object sender, EventArgs e)
        {
            FileArray();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                LoadFile(openFileDialog.FileName);
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileArray();
            LoadForm();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFile();

            APlayer.SavePlayer(APlayer.FilePath);
            string file = Path.GetFileNameWithoutExtension(APlayer.FilePath);
            MessageBox.Show("Saved " + file + "!", "File Saved");
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\My Games\Terraria\Players\";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (APlayer == null)
                    APlayer = new Player(Path.GetFullPath(saveFileDialog.FileName));

                SaveFile();
                APlayer.SavePlayer(saveFileDialog.FileName);
                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.InitialDirectory = Path.GetFullPath(saveFileDialog.FileName);
                APlayer.FilePath = saveFileDialog.InitialDirectory;

                FileArray();

                string file = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                MessageBox.Show("Saved as " + file + "!", "File Saved");
                fileComboBox.Text = file;
                saveToolStripMenuItem.Enabled = true;
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (APlayer != null)
            {
                DialogResult result = MessageBox.Show("Are you sure you want to delete" +
                    "\n" + Path.GetFileName(APlayer.FilePath) + "?",
                    "Delete Player", MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)
                {
                    File.Delete(APlayer.FilePath);
                    APlayer = null;
                    MessageBox.Show("Player Deleted!", "Dooms Day...");
                }
            }

            if (APlayer == null)
            {
                FileArray();
                LoadForm();
            }
        }

        private void launchTerrariaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder str = new StringBuilder("steam: \"");
                str.AppendFormat("-applaunch {0}", 105600);
                str.Append("\"");

                Process.Start(str.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void aboutTerrariViewerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("TerrariViewer " + versionNumber + "\n\nCreated By: TJChap2840\n\nThanks To: \n"
                    + "\nBenji (Fixing the missing images problem) \nwillgk (Tons of troubleshooting)"
                    + "\nZaa Boogie & Smashman (Testing new releases)"
                    + "\nKJHawk2k (Troubleshooting)\nUberJumper (File I/O Help)"
                    + "\nEverDraed (Packaging Terraria Sprites & Icon!)\nRinn (Immense C# help)"
                    + "\nShoot (Helping with \"Launch Terraria\" code)"
                    + "\nKharmakazy (Suggestions and Testing)"
                    + "\nThe Something Awful Community & Redditors", "About TerrariViewer!");
        }

        private void followMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://twitter.com/#!/tjchap2840");
        }

        private void donateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=74TENM4NF4DUN&lc=US&item_name=TerrariViewer&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted");
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string downloadULR = updateCheck.CheckForUpdates("https://hg01.codeplex.com/terrariviewer/raw-file/tip/releases.xml", UpdateChecker.UpdateFilter.Alpha);

            if (downloadULR != "No Updates Available")
            {
                DialogResult result = MessageBox.Show("Updates Available\nDownload Now?", "Update Check", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                    Process.Start(downloadULR);
                else
                    return;
            }
            else
                MessageBox.Show(downloadULR, "Update Check");
        }

        private void submitABugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://terrariviewer.codeplex.com/workitem/list/basic");
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://terrariviewer.codeplex.com/documentation");
        }
        #endregion

        #region Character Tab
        private void cheatCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (cheatCheck.Checked == true)
            {
                maxHealth = "1000";
                maxMana = "1000";
                maxHealthTxtBox.Text = maxHealth;
                maxManaTxtBox.Text = maxMana;
            }
            else
            {
                maxHealth = "400";
                maxMana = "260";

                if (int.Parse(healthTxtBox.Text) > 400)
                    healthTxtBox.Text = maxHealth;

                maxHealthTxtBox.Text = maxHealth;

                if (int.Parse(manaTxtBox.Text) > 260)
                    manaTxtBox.Text = maxMana;

                maxManaTxtBox.Text = maxMana;

                for(int i = 0; i < this.buffs.Length; i++)
                {
                    if (this.buffs[i].BuffType > 0)
                    {
                        this.buffs[i].BuffTime = buffs[i].MaxBuff() * 60;
                        bTimeLabels[i].Text = (this.buffs[i].BuffTime / 60).ToString() + " Seconds";
                        toolTip.SetToolTip(buffBoxes[i], buffs[i].ToString());
                    }
                }

                for (int i = 0; i < this.inv.Length; i++)
                {
                    if (this.inv[i].Name != "" && (this.inv[i].StackSize > this.inv[i].ItemMaxStack()))
                    {
                        this.inv[i].StackSize = inv[i].ItemMaxStack();
                        invBoxes[i].Text = this.inv[i].StackSize.ToString();
                        toolTip.SetToolTip(invBoxes[i], inv[i].ToString());
                    }
                }
                toolTip.SetToolTip(currInvBox, inv[invClicked].ToString());
                invStackTxtBox.Text = inv[invClicked].StackSize.ToString();
                                
                for (int i = 0; i < this.bank.Length; i++)
                {
                    if (this.bank[i].Name != "" && (this.bank[i].StackSize > this.bank[i].ItemMaxStack()))
                    {
                        this.bank[i].StackSize = bank[i].ItemMaxStack();
                        bankBoxes[i].Text = this.bank[i].StackSize.ToString();
                        toolTip.SetToolTip(bankBoxes[i], bank[i].ToString());
                    }
                }
                toolTip.SetToolTip(currBankBox, bank[bankClicked].ToString());
                bankStackTxtBox.Text = bank[bankClicked].StackSize.ToString();
            }
        }

        private void ColorBox_Click(object sender, EventArgs e)
        {
            PictureBox box = (PictureBox)sender;

            colorDialog.Color = box.BackColor;

            if (colorDialog.ShowDialog() != DialogResult.Cancel)
                box.BackColor = colorDialog.Color;

            this.Refresh();
        }

        private void randColorBtn_Click(object sender, EventArgs e)
        {
            for(int i = 0; i < colorBoxes.Count; i++)
                colorBoxes[i].BackColor = tempColor.GetColor((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));

            this.Refresh();
        }

        private void hairNum_ValueChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void randHairBtn_Click(object sender, EventArgs e)
        {
            hairNum.Value = (decimal)random.Next(1, 37);
            this.Refresh();
        }

        private System.Drawing.Image HairImage(int numValue)
        {
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            string item = "TerrariViewer.Resources.Hair_" + numValue.ToString() + ".png";
            System.IO.Stream file = thisExe.GetManifestResourceStream(item);
            return Image.FromStream(file);
        }

        private void healthTxtBox_TextChanged(object sender, EventArgs e)
        {
            if (int.Parse(healthTxtBox.Text) > int.Parse(maxHealthTxtBox.Text))
                healthTxtBox.Text = maxHealthTxtBox.Text;
        }

        private void manaTxtBox_TextChanged(object sender, EventArgs e)
        {
            if (int.Parse(manaTxtBox.Text) > int.Parse(maxManaTxtBox.Text))
                manaTxtBox.Text = maxManaTxtBox.Text;
        }

        private void maxStatButton_Click(object sender, EventArgs e)
        {
            maxHealthTxtBox.Text = maxHealth;
            maxManaTxtBox.Text = maxMana;
        }

        private void maxHealthTxtBox_TextChanged(object sender, EventArgs e)
        {

            if (int.Parse(maxHealthTxtBox.Text) <= int.Parse(healthTxtBox.Text))
            {
                maxHealthTxtBox.Text = healthTxtBox.Text;
            }

            if (cheatCheck.Checked)
            {
                if (int.Parse(maxHealthTxtBox.Text) > 1000)
                    maxHealthTxtBox.Text = "1000";
            }
            else
            {
                if (int.Parse(maxHealthTxtBox.Text) > 400)
                    maxHealthTxtBox.Text = "400";
            }
        }

        private void maxManaTxtBox_TextChanged(object sender, EventArgs e)
        {
            if (int.Parse(maxManaTxtBox.Text) <= int.Parse(manaTxtBox.Text))
                maxManaTxtBox.Text = manaTxtBox.Text;

            if (cheatCheck.Checked)
            {
                if (int.Parse(maxManaTxtBox.Text) > 1000)
                    maxManaTxtBox.Text = "1000";
            }
            else
            {
                if (int.Parse(maxManaTxtBox.Text) > 260)
                    maxManaTxtBox.Text = "260";
            }
        }

        private void healButton_Click(object sender, EventArgs e)
        {
            healthTxtBox.Text = maxHealthTxtBox.Text;
            manaTxtBox.Text = maxManaTxtBox.Text;
        }
        #endregion

        private void ClearLVSelected(ListView lv)
        {
            if (lv.FocusedItem != null)
            {
                ListViewItem item = new ListViewItem();
                item = lv.FocusedItem;
                item.Selected = false;
            }
        }

        #region Equipment Tab
        private void EquipmentBoxes_Click(object sender, EventArgs e)
        {
            ClearLVSelected(equipmentLV);
            PictureBox box = (PictureBox)sender;
            equipmentClicked = equipmentBoxes.IndexOf(box);

            foreach (PictureBox pic in equipmentBoxes)
            {
                pic.BorderStyle = BorderStyle.FixedSingle;
                pic.BackColor = System.Drawing.Color.Transparent;
            }

            box.BorderStyle = BorderStyle.Fixed3D;
            box.BackColor = System.Drawing.Color.FromArgb(222, 222, 222);

            FillEquipmentLV(equipmentClicked);
        }

        private void equipmentLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem item = new ListViewItem();
            item = equipmentLV.FocusedItem;

            if (item != null)
            {
                AssignEquipment(item.Text);
            }
        }

        private void AssignEquipment(string item)
        {
            if (armors.Contains(item) == false)
                if (accs.Contains(item) == false)
                    item = "";
            
            equipment[equipmentClicked] = item;
            equipmentBoxes[equipmentClicked].Image = tempItem.ItemImage(item);
            toolTip.SetToolTip(equipmentBoxes[equipmentClicked], equipment[equipmentClicked]);
        }

        private void FillEquipmentLV(int index)
        {
            int lower = 0;
            int upper = 0;

            switch (index)
            {
                case 0:
                    lower = 0;
                    upper = 14;
                    break;

                case 1:
                    lower = 29;
                    upper = 38;
                    break;

                case 2:
                    lower = 46;
                    upper = 55;
                    break;

                case 3:
                    lower = -1;
                    break;

                case 4:
                    lower = -1;
                    break;

                case 5:
                    lower = -1;
                    break;
                    
                case 6:
                    lower = -1;
                    break;

                case 7:
                    lower = -1;
                    break;

                case 8:
                    lower = 0;
                    upper = 29;
                    break;

                case 9:
                    lower = 29;
                    upper = 46;
                    break;

                case 10:
                    lower = 46;
                    upper = 62;
                    break;
            }

            equipmentLV.Clear();
            equipmentLV.Items.Add("No Item");
            if (lower != -1)
            {
                for (int i = lower; i < upper; i++)
                {
                    equipmentLV.Items.Add(armors[i]);
                }
            }
            else
            {
                for(int i = 0; i < accs.Count; i++)
                {
                    equipmentLV.Items.Add(accs[i]);
                }
            }
        }
        #endregion

        #region Buff Tab
        private void BuffBoxes_Click(object sender, EventArgs e)
        {
            ClearLVSelected(buffLV);
            PictureBox box = (PictureBox)sender;
            buffClicked = buffBoxes.IndexOf(box);

            foreach (PictureBox pic in buffBoxes)
            {
                pic.BorderStyle = BorderStyle.FixedSingle;
                pic.BackColor = System.Drawing.Color.Transparent;
            }

            box.BorderStyle = BorderStyle.Fixed3D;
            box.BackColor = System.Drawing.Color.FromArgb(222, 222, 222);
        }

        private void maxBuffBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.buffs.Length; i++)
            {
                if (buffs[i].BuffType > 0)
                {
                    if (cheatCheck.Checked == true)
                    {
                        this.buffs[i].BuffTime = 216000;
                        bTimeLabels[i].Text = "3600 Seconds";
                    }
                    else
                    {
                        this.buffs[i].BuffTime = (this.buffs[i].MaxBuff() * 60);
                        bTimeLabels[i].Text = (this.buffs[i].MaxBuff()).ToString() + " Seconds";
                    }

                    toolTip.SetToolTip(buffBoxes[i], buffs[i].ToString());
                }
            }
        }

        private void AssignBuff(int buff)
        {
            if (buff > 0)
            {
                buffs[buffClicked].BuffType = buff;
                buffBoxes[buffClicked].Image = buffs[buffClicked].BuffImages();
                buffLabels[buffClicked].Text = buffs[buffClicked].BuffName();

                if (cheatCheck.Checked == true)
                {
                    this.buffs[buffClicked].BuffTime = 216000;
                    bTimeLabels[buffClicked].Text = "3600 Seconds";
                }
                else
                {
                    this.buffs[buffClicked].BuffTime = (this.buffs[buffClicked].MaxBuff() * 60);
                    bTimeLabels[buffClicked].Text = (this.buffs[buffClicked].MaxBuff()).ToString() + " Seconds";
                }

                toolTip.SetToolTip(buffBoxes[buffClicked], buffs[buffClicked].ToString());
            }
            else
            {
                buffs[buffClicked].BuffType = buff;
                buffs[buffClicked].BuffTime = 0;
                buffBoxes[buffClicked].Image = buffs[buffClicked].BuffImages();
                buffLabels[buffClicked].Text = "";
                bTimeLabels[buffClicked].Text = "";
            }
        }

        private void buffLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (buffClicked != -1)
            {
                ListViewItem item = new ListViewItem();
                item = buffLV.FocusedItem;

                if (item != null)
                {
                    AssignBuff(item.Index);
                }
            }
        }
        #endregion

        #region Inventory Tab
        private void InvBoxes_Click(object sender, EventArgs e)
        {
            ClearLVSelected(invLV);
            Label lbl = (Label)sender;
            invClicked = invBoxes.IndexOf(lbl);

            if (!(this.inv[invClicked].Name.Length > 0))
            {
                currInvLbl.Text = "";
                currInvBox.Image = tempItem.ItemImage();
                invStackTxtBox.Text = "0";
                invStackTxtBox.Enabled = false;
            }
            else
            {
                currInvLbl.Text = this.inv[invClicked].Name;
                currInvBox.Image = this.inv[invClicked].ItemImage();
                invStackTxtBox.Text = this.inv[invClicked].StackSize.ToString();
                invStackTxtBox.Enabled = true;
                toolTip.SetToolTip(currInvBox, inv[invClicked].ToString());
            }

            if (invClicked > 43)
            {
                invSearchTxtBox.Text = "";
                invSearchTxtBox.ReadOnly = true;
                invCategories.Enabled = false;
                invCategories.Text = "Ammunition";
            }
            else if (invClicked > 39 && invClicked < 44)
            {
                invSearchTxtBox.Text = "Coin";
                invSearchTxtBox.ReadOnly = true;
                invCategories.Enabled = false;
            }
            else
            {
                invSearchTxtBox.Text = "";
                invSearchTxtBox.ReadOnly = false;
                invCategories.Enabled = true;
                invCategories.Text = "All";
            }

            foreach (Label label in invBoxes)
            {
                label.BorderStyle = BorderStyle.FixedSingle;
                label.BackColor = System.Drawing.Color.Transparent;
            }

            lbl.BorderStyle = BorderStyle.Fixed3D;
            lbl.BackColor = System.Drawing.Color.FromArgb(222, 222, 222);
        }

        private void invStackTxtBox_TextChanged(object sender, EventArgs e)
        {
            if (invClicked != -1)
            {
                if (invStackTxtBox.Text.Length == 0)
                    invStackTxtBox.Text = "1";

                int max = this.inv[invClicked].ItemMaxStack();
                if (cheatCheck.Checked)
                    max = 999;

                if (int.Parse(invStackTxtBox.Text) > max)
                    invStackTxtBox.Text = max.ToString();

                this.inv[invClicked].StackSize = int.Parse(invStackTxtBox.Text);
                invBoxes[invClicked].Text = this.inv[invClicked].StackSize.ToString();
            }
        }

        private void invMaxBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.inv.Length; i++)
            {
                int max = this.inv[i].ItemMaxStack();
                if (cheatCheck.Checked)
                    max = 999;

                if (this.inv[i].Name.Length > 0)
                {
                    this.inv[i].StackSize = max;
                    invBoxes[i].Text = max.ToString();
                    invStackTxtBox.Text = inv[invClicked].StackSize.ToString();
                    toolTip.SetToolTip(invBoxes[i], inv[i].ToString());
                }
            }

            toolTip.SetToolTip(currInvBox, inv[invClicked].ToString());
        }

        private void InvAssign(string item)
        {
            if (items.Contains(item) == false)
                item = "";

            inv[invClicked].Name = item;
            if (cheatCheck.Checked && !(inv[invClicked].Name == ""))
                inv[invClicked].StackSize = 999;
            else
                inv[invClicked].StackSize = inv[invClicked].ItemMaxStack();

            currInvBox.Image = inv[invClicked].ItemImage();
            currInvLbl.Text = inv[invClicked].Name;
            invStackTxtBox.Text = inv[invClicked].StackSize.ToString();
            invBoxes[invClicked].Image = inv[invClicked].ItemImage();

            if (inv[invClicked].Name == "")
                invStackTxtBox.Enabled = false;
            else
                invStackTxtBox.Enabled = true;

            toolTip.SetToolTip(invBoxes[invClicked], inv[invClicked].ToString());
            toolTip.SetToolTip(currInvBox, inv[invClicked].ToString());
        }
        #endregion

        #region Bank Tab
        private void BankBoxes_Click(object sender, EventArgs e)
        {
            ClearLVSelected(bankLV);
            Label lbl = (Label)sender;
            bankClicked = bankBoxes.IndexOf(lbl);

            if (!(this.bank[bankClicked].Name.Length > 0))
            {
                currBankLbl.Text = "";
                currBankBox.Image = tempItem.ItemImage();
                bankStackTxtBox.Text = "0";
                bankStackTxtBox.Enabled = false;
            }
            else
            {
                currBankLbl.Text = this.bank[bankClicked].Name;
                currBankBox.Image = this.bank[bankClicked].ItemImage();
                bankStackTxtBox.Text = this.bank[bankClicked].StackSize.ToString();
                bankStackTxtBox.Enabled = true;
                toolTip.SetToolTip(currBankBox, bank[bankClicked].ToString());
            }

            foreach (Label label in bankBoxes)
            {
                label.BorderStyle = BorderStyle.FixedSingle;
                label.BackColor = System.Drawing.Color.Transparent;
            }

            lbl.BorderStyle = BorderStyle.Fixed3D;
            lbl.BackColor = System.Drawing.Color.FromArgb(222, 222, 222);
        }

        private void bankStackTxtBox_TextChanged(object sender, EventArgs e)
        {
            if (bankClicked != -1)
            {
                if (bankStackTxtBox.Text.Length == 0)
                    bankStackTxtBox.Text = "1";

                int max = this.bank[bankClicked].ItemMaxStack();
                if (cheatCheck.Checked)
                    max = 999;

                if (int.Parse(bankStackTxtBox.Text) > max)
                    bankStackTxtBox.Text = max.ToString();

                this.bank[bankClicked].StackSize = int.Parse(bankStackTxtBox.Text);
                bankBoxes[bankClicked].Text = this.bank[bankClicked].StackSize.ToString();
            }
        }

        private void bankMaxBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.bank.Length; i++)
            {
                int max = this.bank[i].ItemMaxStack();
                if (cheatCheck.Checked)
                    max = 999;

                if (this.bank[i].Name.Length > 0)
                {
                    this.bank[i].StackSize = max;
                    bankBoxes[i].Text = max.ToString();
                    bankStackTxtBox.Text = bank[bankClicked].StackSize.ToString();
                    toolTip.SetToolTip(bankBoxes[i], bank[i].ToString());
                }
            }

            toolTip.SetToolTip(currBankBox, bank[bankClicked].ToString());
        }

        private void BankAssign(string item)
        {
            if (items.Contains(item) == false)
                    item = "";

            bank[bankClicked].Name = item;
            if (cheatCheck.Checked && !(bank[bankClicked].Name == ""))
                bank[bankClicked].StackSize = 999;
            else
                bank[bankClicked].StackSize = bank[bankClicked].ItemMaxStack();

            currBankBox.Image = bank[bankClicked].ItemImage();
            currBankLbl.Text = bank[bankClicked].Name;
            bankStackTxtBox.Text = bank[bankClicked].StackSize.ToString();
            bankBoxes[bankClicked].Image = bank[bankClicked].ItemImage();

            if (bank[bankClicked].Name == "")
                bankStackTxtBox.Enabled = false;
            else
                bankStackTxtBox.Enabled = true;

            toolTip.SetToolTip(bankBoxes[bankClicked], bank[bankClicked].ToString());
            toolTip.SetToolTip(currBankBox, bank[bankClicked].ToString());
        }
        #endregion

        #region Inventory/Bank Functions

        private void ItemSearchTxtBox_TextChanged(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;
            ListView currLV = new ListView();
            List<string> results = new List<string> { };

            if (txt == bankSearchTxtBox)
                currLV = bankLV;
            else
                currLV = invLV;

            string search = txt.Text.ToLower();

            foreach (string s in items)
            {
                if (s.ToLower().Contains(search))
                {
                    results.Add(s);
                }
            }

            RefreshItemLV(results, currLV);
        }

        private void ItemCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox combo = (ComboBox)sender;

            ListView currLV = new ListView();

            if (combo == bankCategories)
                currLV = bankLV;
            else
                currLV = invLV;

            switch (combo.SelectedIndex)
            {
                case 0:
                    RefreshItemLV(items, currLV);
                    break;

                case 1:
                    RefreshItemLV(armors, currLV);
                    break;

                case 2:
                    RefreshItemLV(accs, currLV);
                    break;

                case 3:
                    RefreshItemLV(weapons, currLV);
                    break;

                case 4:
                    RefreshItemLV(ammunition, currLV);
                    break;

                case 5:
                    RefreshItemLV(tools, currLV);
                    break;

                case 6:
                    RefreshItemLV(consumables, currLV);
                    break;

                case 7:
                    RefreshItemLV(furnitures, currLV);
                    break;

                case 8:
                    RefreshItemLV(blocks, currLV);
                    break;

                case 9:
                    RefreshItemLV(misc, currLV);
                    break;
            }
        }

        private void ItemLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListView currLV = (ListView)sender;

            ListViewItem item = new ListViewItem();
            item = currLV.FocusedItem;

            if (item != null)
            {
                if (currLV == bankLV)
                    BankAssign(item.Text);
                else
                    InvAssign(item.Text);
            }
        }

        private void RefreshItemLV(List<string> list, ListView lv)
        {
            List<string> tempList = list.ConvertAll(delegate(string input) { return input; });

            tempList.Sort();
            lv.Clear();

            lv.Items.Add("No Item");
            foreach (string str in tempList)
                lv.Items.Add(str);
        }

        #endregion

        private Bitmap DrawCharacter(Bitmap bmp, System.Drawing.Color color, int w, int h)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                for (int x = 0; x < bmp.Width; x++)
                {
                    System.Drawing.Color pixel = bmp.GetPixel(x, y);

                    if (pixel != System.Drawing.Color.FromArgb(0, 0, 0, 0))
                    {
                        if (pixel == System.Drawing.Color.FromArgb(255, 249, 249, 249))
                            bmp.SetPixel(x, y, System.Drawing.Color.White);
                        else
                        {
                            int red = (pixel.R + color.R) / 2;
                            int green = (pixel.G + color.G) / 2;
                            int blue = (pixel.B + color.B) / 2;
                            bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(red,
                                                                             green,
                                                                             blue));
                        }
                    }
                }
            }

            Bitmap newImage = new Bitmap(w, h);
            using (Graphics g = Graphics.FromImage(newImage))
            {
                g.InterpolationMode = InterpolationMode.NearestNeighbor;
                g.DrawImage(bmp, new Rectangle(0, 0, w, h));
            }

            return newImage;
        }

        /*public void RefreshCharacter(PictureBox box)
        {
            Graphics g = CreateGraphics();

            Bitmap redraw;

            switch (box.Name)
            {
                case "hairClrBox":
                    hair = DrawCharacter(new Bitmap(HairImage((int)hairNum.Value)), box.BackColor, 120, 120);
                    redraw = hair;
                    break;

                case "skinClrBox":
                    skin = DrawCharacter(new Bitmap(Properties.Resources.Hands), box.BackColor, 120, 120);
                    head = DrawCharacter(new Bitmap(Properties.Resources.Head), box.BackColor, 120, 120);
                    redraw = skin;
                    break;

                case "eyeClrBox":
                    eyes = DrawCharacter(new Bitmap(Properties.Resources.Eyes), box.BackColor, 40, 40);
                    redraw = eyes;
                    break;

                case "shirtClrBox":
                    shirt = DrawCharacter(new Bitmap(Properties.Resources.Shirt), box.BackColor, 120, 120);
                    redraw = shirt;
                    break;

                case "ushirtClrBox":
                    undershirt = DrawCharacter(new Bitmap(Properties.Resources.Undershirt), box.BackColor, 120, 120);
                    redraw = undershirt;
                    break;

                case "pantsClrBox":
                    pants = DrawCharacter(new Bitmap(Properties.Resources.Pants), box.BackColor, 120, 120);
                    redraw = pants;
                    break;

                case "shoeClrBox":
                    shoes = DrawCharacter(new Bitmap(Properties.Resources.shoes), box.BackColor, 65, 65);
                    break;
            }

            g.Dispose();
        }*/

        private void appearanceBox_Paint(object sender, PaintEventArgs e)
        {
            hair = DrawCharacter(new Bitmap(HairImage((int)hairNum.Value)), hairClrBox.BackColor, 120, 120);
            skin = DrawCharacter(new Bitmap(Properties.Resources.Hands), skinClrBox.BackColor, 120, 120);
            head = DrawCharacter(new Bitmap(Properties.Resources.Head), skinClrBox.BackColor, 120, 120);
            eyes = DrawCharacter(new Bitmap(Properties.Resources.Eyes), eyeClrBox.BackColor, 40, 40);
            shirt = DrawCharacter(new Bitmap(Properties.Resources.Shirt), shirtClrBox.BackColor, 120, 120);
            undershirt = DrawCharacter(new Bitmap(Properties.Resources.Undershirt), ushirtClrBox.BackColor, 120, 120);
            pants = DrawCharacter(new Bitmap(Properties.Resources.Pants), pantsClrBox.BackColor, 120, 120);
            shoes = DrawCharacter(new Bitmap(Properties.Resources.shoes), shoeClrBox.BackColor, 65, 65);

            Graphics g = e.Graphics;

            if (dpiX == 120.0)
            {
                g.DrawImage(pants, 274, 151);
                g.DrawImage(shoes, 311, 190);
                g.DrawImage(shirt, 274, 112);
                g.DrawImage(undershirt, 274, 112);
                g.DrawImage(skin, 274, 113);
                g.DrawImage(head, 274, 65);
                g.DrawImage(eyes, 318, 112);
                g.DrawImage(hair, 272, 65);
            }
            else
            {
                g.DrawImage(pants, 194, 127);
                g.DrawImage(shoes, 231, 166);
                g.DrawImage(shirt, 194, 88);
                g.DrawImage(undershirt, 194, 88);
                g.DrawImage(skin, 194, 88);
                g.DrawImage(head, 194, 41);
                g.DrawImage(eyes, 238, 88);
                g.DrawImage(hair, 192, 41);
            }
        }

        private void Box_MouseEnter(object sender, EventArgs e)
        {
            SenderConversion(sender);

            if (selectedBox.BackColor == System.Drawing.Color.FromArgb(222, 222, 222) || selectedLbl.BackColor == System.Drawing.Color.FromArgb(222, 222, 222))
            {
                ctrl.BackColor = System.Drawing.Color.FromArgb(200, 200, 200);
            }
            else
            {
                ctrl.BackColor = System.Drawing.Color.YellowGreen;
            }            
        }

        private void Box_MouseLeave(object sender, EventArgs e)
        {
            SenderConversion(sender);

            if (selectedBox.BorderStyle == BorderStyle.Fixed3D || selectedLbl.BorderStyle == BorderStyle.Fixed3D)
            {
                ctrl.BackColor = System.Drawing.Color.FromArgb(222, 222, 222);
            }
            else
            {
                ctrl.BackColor = System.Drawing.Color.Transparent;
            }
        }

        private void SenderConversion(object sender)
        {
            type = sender.GetType();
            ctrl = (Control)sender;
            selectedBox = new PictureBox();
            selectedLbl = new Label();

            if (type.Name == "PictureBox")
            {
                selectedBox = (PictureBox)sender;
            }
            else
            {
                selectedLbl = (Label)sender;
            }
        }
    }
}
